package com.atguigu.juc1205.fileoperation;

import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author Joey
 * @Date 2021/11/15 13:48
 * @Description
 */
public class WorkTime {

    public static void main(String[] args) throws JSONException {
        List<OriginalData> data = null;
        try {
            data = ExcelUtil.getData("D://xzq//公司/签卡数据 -2021.10.澳门北京原始.xls");
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, List<OriginalData>> originalDataList = getOriginalDataListGroupByName(data);




        JSONObject result = getResult(originalDataList);
        System.out.println(result);

    }

    /**
     * @param originalDataList 按姓名分组的数据
     * @return 处理结果
     * @throws JSONException
     */
    private static JSONObject getResult(Map<String, List<OriginalData>> originalDataList) throws JSONException {
        JSONObject result = new JSONObject();
        for (String name : originalDataList.keySet()) {
            List<OriginalData> dates = originalDataList.get(name);
            Map<String, List<String>> dateListBySignTime = getDateListGroupBySignTime(dates);
            result.put(name, removeNonUsedDate(dateListBySignTime));
        }
        return result;
    }

    /**
     * @param dates 按姓名分组后的数据
     * @return 按日期分组后的数据
     */
    private static Map<String, List<String>> getDateListGroupBySignTime(List<OriginalData> dates) {
        return dates.stream().collect(
                Collectors.groupingBy(OriginalData::getDate, Collectors.mapping(OriginalData::getSignTime, Collectors.toList())));
    }

    /**
     * @param data 原始数据
     * @return 按姓名分组的数据
     */
    private static Map<String, List<OriginalData>> getOriginalDataListGroupByName(List<OriginalData> data) {
        return data.stream().collect(Collectors.groupingBy(OriginalData::getName));
    }

    /**
     * @param dateListBySignTime 按日期分组后的数据
     * @return 去除无用日期后的数据
     * @throws JSONException
     */
    private static Map<String, List<String>> removeNonUsedDate(Map<String, List<String>> dateListBySignTime) {
        for (String date : dateListBySignTime.keySet()) {
            List<String> dates1 = dateListBySignTime.get(date);
            if (dates1.size() > 2){
                dates1.set(1,dates1.get(dates1.size()-1));
                for (int i = 2; i < dates1.size(); i++) {
                    dates1.remove(i);
                }
            }
            dateListBySignTime.put(date,dates1);
        }
        return dateListBySignTime;
    }

}
